package com.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.blog.bo.BlogIpAddressBO;
import com.blog.entity.BlogIpAddress;
import com.blog.service.IpAddressService;
import com.blog.utils.BusinessException;
import com.blog.utils.IpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author Huangzp
 * @Date 2022/1/10 14:42
 */
@Slf4j
@Service
public class IpAddressServiceImpl implements IpAddressService {

    @Autowired
    private BlogIpAddressBO blogIpAddressBO;


    @Override
    public List<BlogIpAddress> selectList(BlogIpAddress address) {
        return blogIpAddressBO.selectList(address);
    }

    @Override
    public List<BlogIpAddress> selectIpByManagerId(Integer managerId) {
        QueryWrapper<BlogIpAddress> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(BlogIpAddress::getManagerId,managerId);
        return blogIpAddressBO.list(queryWrapper);
    }

    @Override
    public void update(Integer id) {
        try {
            QueryWrapper<BlogIpAddress> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(BlogIpAddress::getManagerId,id);
            List<BlogIpAddress> ipAddresses = blogIpAddressBO.list(queryWrapper);

            if(ipAddresses.stream().anyMatch(x->x.getIp().equals(IpUtil.getIpAddr()))){
                //如果已经存在ip，则修改ip访问时间
                BlogIpAddress address = ipAddresses.stream().filter(f -> f.getIp().equals(IpUtil.getIpAddr())).findAny().orElse(null);
                blogIpAddressBO.updateById(address);
            }else {
                //不存在则新加入一条访问ip
                BlogIpAddress ipAddress = new BlogIpAddress();
                ipAddress.setIp(IpUtil.getIpAddr());
                ipAddress.setManagerId(id);
                blogIpAddressBO.save(ipAddress);
            }

        }catch (BusinessException e) {
            throw new BusinessException("注册失败！",e.getErrorMessage());
        }
    }
}
